package org.example.mybatisplus.controller;

import org.example.mybatisplus.dao.entity.Student;
import org.example.mybatisplus.service.IStudentService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Description: java类作用描述 TODO
 * @Author: renml
 * @CreateDate: 2025/5/22 15:30
 * @UpdateUser: renml
 * @UpdateDate: 2025/5/22 15:30
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@RestController
@RequestMapping("/redisson")
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IStudentService studentService;

    @RequestMapping("/getAge")
    //public String getAge() {
    public synchronized String getAge() {
        Student byId = studentService.getById(1389080578L);
        if (byId != null) {
            if (byId.getAge() > 1) {
                studentService.lambdaUpdate()
                        .setSql("age = age - 1")
                        .eq(Student::getId, byId.getId())
                        .update();
            } else {
                return byId.getAge().toString();
            }
        }
        return byId.getAge().toString();
    }


    @RequestMapping("/buy")
    public String buy() {
        // 获取锁对象，"myLock" 是锁的 key
        RLock lock = redissonClient.getLock("myLock123456");
        boolean isLocked = false;
        try {
            // 尝试获取锁，等待时间 10 秒，锁租期 60 秒
            isLocked = lock.tryLock(10, 60, TimeUnit.SECONDS);
            if (isLocked) {
                System.out.println("Lock acquired by thread: " + Thread.currentThread().getName());
                Student byId = studentService.getById(1389080578L);
                if (byId != null) {
                    System.out.println("Current age: " + byId.getAge());
                    if (byId.getAge() > 1) {
                        byId.setAge(byId.getAge() - 1);
                        studentService.lambdaUpdate().set(Student::getAge, byId.getAge()).eq(Student::getId, byId.getId()).update();
                        System.out.println("Age updated to: " + byId.getAge());
                    } else {
                        return "Age is less than or equal to 1";
                    }
                } else {
                    return "Student not found";
                }
            } else {
                // 未获取到锁
                System.out.println("Failed to acquire lock by thread: " + Thread.currentThread().getName());
                return "Failed to acquire lock!";
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("Operation interrupted by thread: " + Thread.currentThread().getName());
            return "Operation interrupted!";
        } finally {
            // 释放锁（仅在获取锁的情况下释放）
            if (isLocked) {
                lock.unlock();
                System.out.println("Lock released by thread: " + Thread.currentThread().getName());
            }
        }
        return "ok";
    }
}